const { Post,
    Get,
    Controller,
    middlewarePost
} = require("../decorator/router")
const { User } = require('../dataDB/user')
const { IPHONE_DETAILS_MODEL } = require('../dataDB/homeData')
const { mongoose } = require('../mongoose/conectDB')
const { prosime,
    forObj,
    dataErrorReturn,
    pawwordBcrypt
} = require('../util/util')
const createToken = require('../token/createToken')
const fs = require('fs')
const path = require('path')
const formidable = require('formidable')
function objId(id) {
    return mongoose.Types.ObjectId(id)
}

@Controller("/user")
class register {
    @Post("/register")
    async register(ctx, next) {
        let body = ctx.request.body
        let user = new User(body)
        try {
            let data = await new Promise((resolve, reject) => {
                user.save((err, _user) => {
                    if (err) {
                        reject({
                            result: 1,
                            err
                        })
                        return
                    }
                    resolve({
                        result: 1,
                        _user
                    })
                })
            })
            if (data.result === 1) {
                ctx.body = {
                    result: 1,
                    success: true
                }
            }
        } catch (err) {
            try {
                let doc = await prosime({
                    model: User,
                    Keyword: 'findOne',
                    parameter: [
                        { userName: body.userName }
                    ]
                })
                if (doc.userName === body.userName) {
                    ctx.body = {
                        result: 1,
                        theSameusername: false,
                        userName: doc.userName
                    }
                }
            } catch (e) {
                console.log(e)
            }
        }
    }
    
    @Get("/queryUserName")
    async queryUserName(ctx, next) {
        let query = ctx.query
        let dataDB = await User.findOne(query)
        if (dataDB !== null) {
            if (dataDB.userName === query.userName) {
                ctx.body = {
                    result: 1,
                    message: false,
                    userName: dataDB.userName
                }
            }
        } else {
            ctx.body = {
                result: 1,
                message: true
            }
        }
    }

    @Get('/information')
    async information(ctx, next) {
        let id = ctx.query.id
        let data = await User.findById(id, {
            __v: false,
            meta: false,
            date: false,
            password: false
        })
        ctx.body = {
            result: 1,
            message: '登录成功',
            success: true,
            user: data
        }
    }
}

@Controller("/login")
class login {
    @Post('/login')
    async loginAccount(ctx, next) {
        let body = ctx.request.body
        if (body.userName.indexOf('@') !== -1) {
            body['email'] = body.userName
            delete body.userName
        }
        let obj = body.userName === undefined ? { email: body.email } : { userName: body.userName }
        try {
            let user = await User.findOne(obj, {
                meta: false,
                __v: false,
                date: false,
            })
            if (user !== null) {
                let password = await user.cpmparePassword(body.password)
                if (password === true) {
                    ctx.session = {
                        user: user.userName
                    }
                    let users = await User.findOne(obj, {
                        meta: false,
                        __v: false,
                        date: false,
                        password: false
                    })

                    ctx.body = {
                        result: 1,
                        message: '登录成功3秒后跳转之前的页面',
                        success: true,
                        user: users
                    }
                } else {
                    ctx.body = {
                        result: 1,
                        message: '用户名不存在或密码错误',
                        success: false
                    }
                }
                return
            }
            ctx.body = {
                result: 1,
                message: '用户名不存在或密码错误',
                success: false
            }
        } catch (e) {
            console.log(e)
        }
    }
    @middlewarePost('/login')
    async middlewarePost(ctx, next) {
        // console.log(ctx.request.headers)
        return next()
    }
    @Get('/loginOut')
    async loginOut(ctx, next) {
        delete ctx.session.user
        ctx.body = {
            message: true
        }
    }
    @Post('/updateUserName')
    async updateUserName(ctx, next) {
        let odlUserName = ctx.request.body.odlUserName
        let newUserName = ctx.request.body.newUserName
        try {
            let dataUrl = await User.update(odlUserName, { $set: newUserName })
            dataErrorReturn({ dataUrl, ctx })
        } catch (e) {
            ctx.body = {
                result: 0,
                message: '修改失败'
            }
        }
    }

    @Post('/updatePassword')
    async updatePassword(ctx, next) {
        let oldPassword = ctx.request.body.oldPassword
        let newPassword = ctx.request.body.newPassword
        let userName = ctx.request.body.userName
        let user = await User.findOne(userName)
        let pass = await user.cpmparePassword(oldPassword)
        if (pass === false) {
            ctx.body = {
                result: 1,
                message: '原始密码错误',
                success: false
            }
            return
        }
        let password = await pawwordBcrypt(newPassword)
        let dataUrl = await User.update(userName, { $set: { password: password } })
        dataErrorReturn({ dataUrl, ctx })
    }
}

@Controller('/collection')
class collection {

    @Get('/select')
    async select(ctx, next) {
        let query = ctx.query
        let dataUrl = ''
        if (query.select) {
            dataUrl = await IPHONE_DETAILS_MODEL.update({ 'id.id': query.id }, { $set: { select: query.select } })
        } else {
            dataUrl = await IPHONE_DETAILS_MODEL.findOne({ 'id.id': query.id })
        }
        dataErrorReturn({ dataUrl, ctx })
    }

    @Post('/collection')
    async collection(ctx, next) {
        let body = ctx.request.body
        let dataUrl = null
        if (body.find) {
            let _id = body.id
            dataUrl = await User.findById(_id, { collections: true, _id: false })
        } else {
            let collecs = `collections.${body.id}`
            let obj = { $set: {} }
            obj.$set[collecs] = body
            dataUrl = await User.update({ userName: body.userName }, obj)
        }
            
        dataErrorReturn({ dataUrl, ctx })
    }

    @Post('/deleteCollection')
    async deleteCollection(ctx, next) {
        let body = ctx.request.body
        let arrId = body.id
        let obj = {$unset: {}}
        
        arrId.forEach((item, index) => {
            let collecs = `collections.${item}`
            obj.$unset[collecs] = ''
        })
        let data = await User.update({ _id: objId(body.user_id)}, obj)
        // let doc = await IPHONE_DETAILS_MODEL.update({ "id.id": { $in: arrId } },
        //     { $set: { select: false }},
        //     {multi: true}
        // )
        // let dataUrl = [data, doc]
        // console.log(data)
        // console.log(doc)
        if (data.nModified !== 0) {
            ctx.body = {
                code: 1,
                result: data,
                success: true
            };
        }
    }
}

// ;(async () => {
//     let data = await User.update({ _id: objId('5b06d5caca6df148c05d30e4')}, 
//         {"$unset":{"collections.2018_iphone_0":'',"collections.2018_iphone_2":''}}
//     )
//     console.log(data)
// })() 
